<?php

class URLVariables {
	private $_query_array;
	
	function __construct($vars_string = null){
		if ($vars_string == null)
			$vars_string = $_SERVER["QUERY_STRING"];
		parse_str($vars_string, $this->_query_array);
	}
	
	public function fromArray($array){
		$this->_query_array = $array;
	}
	
	public function addArray(array $array){
		$this->_query_array = array_merge($this->_query_array, $array);
	}
	
	public function addVar($var, $value, $vars_string = null){
		self::checkQueryString($vars_string);
		$this->_query_array[$var] = $value;
	}
	
	public function removeVar($var, $vars_string = null){
		self::checkQueryString($vars_string);
		$splice_array = array();
		foreach ($this->_query_array as $k => $v)
			if ($k != $var)
				$splice_array[$k] = $v;
		$this->_query_array = $splice_array;
	}
	
	public function removeVars(array $vars, $vars_string = null) {
		if ($vars_string != null)
			$this->addArrayToVars($vars_string);
		foreach ($vars as $v)
			$this->removeVar($v);
	}
	
	public function leaveVars(array $keys) {
		$this->_query_array = array_intersect_key($this->_query_array, array_flip($keys));
	}
	
	public function getString($preffix = null){
		$string = self::convertArrayToQueryString($this->_query_array);
		if (strlen($preffix) && count($this->_query_array))
			return $preffix.$string;
		return $string;
	}
	
	public function setString($vars_string){
		parse_str($vars_string, $this->_query_array);
	}
	
	private function checkQueryString($vars_string = null){
		if ($vars_string != null)
			parse_str($vars_string, $this->_query_array);
	}
	
	private function convertArrayToQueryString(array $array){
		$strArray = array();
		foreach ($array as $k => $v)
			$strArray[] = $k.'='.$v;
		return join('&', $strArray);
	}
	
	public function clean(){
		$this->_query_array = array();
	}
}

?>
